package com.xm.xmapp.app;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;

import cn.jpush.android.api.JPushInterface;

import com.alibaba.fastjson.JSON;
import com.amap.api.maps.model.LatLng;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.utils.Log;

import com.xm.xmapp.app.CodeConstant;
import com.xm.xmapp.app.MyActivityLifecycleCallbacks;
import com.xm.xmapp.base.BaseInterFace;
import com.xm.xmapp.exception.MyException;
import com.xm.xmapp.http.GetDataErrorListener;
import com.xm.xmapp.http.PostRequest;
import com.xm.xmapp.http.VolleyHttpUpLoad;
import com.xm.xmapp.myinterface.DisssmissInterFace;
import com.xm.xmapp.myinterface.GetDataInterFace;
import com.xm.xmapp.request.bean.BaseBeanRequest;
import com.xm.xmapp.request.bean.StartRequest;
import com.xm.xmapp.response.bean.ResponseStartApp;
import com.xm.xmapp.response.bean.ResponseUserBean;
import com.xm.xmapp.tools.Helper_SharedPreferences;
import com.xm.xmapp.tools.Tools;

public class MyAppcation extends Application {

	private static MyAppcation instence;
	private RequestQueue requestQueue;
	private ResponseUserBean userBean;
	private SQLiteDatabase db;
	public int get_money_second = 30;
	private int map_update_second = 30;

	private Location location;
	public boolean isFirstInter = false;
	private ArrayList<BaseInterFace> list;

	public Location getLocation() {
		return location;
	}
	public LatLng getMyLocation(){
		if (location==null)
		return null;
		return new LatLng(location.getLatitude(),location.getLongitude());
	}


	public void setLocation(Location location){
		this.location = location;
	}

	public int getMap_update_second() {
		if (map_update_second == 0)
			return 30 * 1000;
		return map_update_second * 1000;
	}

	public static MyAppcation getMyAppcation() {
		return instence;
	}

	public ArrayList<BaseInterFace> getList() {
		return list;
	}

	/**
	 * 获取顶部activity
	 *
	 * @return
	 */
	public Activity getTopActivity() {
		int size = list.size();
		for (int i = (size - 1); i >= 0; i--) {
			if (list.get(i) instanceof Activity)
				return (Activity) list.get(i);

		}
		return null;
	}

	public void setList(ArrayList<BaseInterFace> list) {
		this.list = list;
	}

	{
		PlatformConfig.setWeixin(CodeConstant.wechatAppId, CodeConstant.wechatAppSecret);
		PlatformConfig.setSinaWeibo(CodeConstant.sinaAppId, CodeConstant.sinaAppSecret,
				"http://sns.whalecloud.com/sina2/callback");
		PlatformConfig.setQQZone(CodeConstant.qqAppId, CodeConstant.qqAppSecret);
	}

	public String getUid() {
		if (getUserBean() != null) {
			return getUserBean().user_id;
		} else {
			return "";
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onCreate() {
		instence = this;
		super.onCreate();
		requestQueue = Volley.newRequestQueue(this);
		isFirstInter = true;
		JPushInterface.init(this); // 初始化 JPush
		list = new ArrayList<BaseInterFace>();
		ImageLoaderConfiguration config = ImageLoaderConfiguration.createDefault(this);
		ImageLoader.getInstance().init(config);
		// 初始化数据
		createDatabase(getApplicationContext());
		StartRequest requestBean = new StartRequest();
		getPostData(this, requestBean, new GetDataInterFace<String>() {

			@Override
			public void onResponse(String response) {

				try {
					ResponseStartApp base = JSON.parseObject(response, ResponseStartApp.class);
					MyAppcation.getMyAppcation().get_money_second = base.get_money_second;
					MyAppcation.getMyAppcation().map_update_second = base.map_update_second;
				} catch (Exception e) {
					MyException.printStackTrace(e);
				}
			}
		}, null);
		UMShareAPI.get(this);
		JPushInterface.setDebugMode(false); // 设置开启日志,发布时请关闭日志

		registerActivityLifecycleCallbacks(new MyActivityLifecycleCallbacks());


	}




	/**
	 * 保存极光ID
	 */
	private void saveJpush_id(String jpush_id) {

		if (jpush_id != null && !jpush_id.trim().equals(""))
			Helper_SharedPreferences.set_str_sp("jpush_id", jpush_id);

	}

	/**
	 * 获取极光ID
	 */
	public String getJpush_id() {
		String jpush_id = Helper_SharedPreferences.get_str_sp("jpush_id");
		if (jpush_id != null) {
			return jpush_id;
		} else {
			jpush_id = JPushInterface.getRegistrationID(this);
			saveJpush_id(jpush_id);
			return jpush_id;
		}
	}

	/**
	 * 保存用戶信息
	 */
	public void saveUserBean(ResponseUserBean bean) {
		Helper_SharedPreferences.set_obj_sp("user", bean);
	}

	/**
	 * 清除用户信息
	 */
	public void clearUserBean() {
		userBean = null;
		Helper_SharedPreferences.clear_sharePref("user");
	}

	/**
	 * 获取用户信息
	 *
	 */

	public ResponseUserBean getUserBean() {
		userBean = (ResponseUserBean) Helper_SharedPreferences.get_obj_sp("user");
		return userBean;
	}

	/**
	 * 创建数据库和表
	 */

	public void createDatabase(Context context) {

		String dbFilePath = "";
		String dataPath = context.getFilesDir().getAbsolutePath();
		File dir = new File(dataPath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		dbFilePath = dataPath + "/" + CodeConstant.DB_NAME;
		db = SQLiteDatabase.openOrCreateDatabase(dbFilePath, null);
		createTable(CodeConstant.System_message, CodeConstant.System_message_id);
		createTable(CodeConstant.Activity_message, CodeConstant.Activity_id);
		createTable(CodeConstant.User_message, CodeConstant.User_message_id);

	}

	public int queryDataSearch_Nun(String tablename, String id, String value) {
		int count;
		Cursor cursor = db.rawQuery("select * from " + tablename + " where " + id + "=?", new String[] { value });
		if (null == cursor || cursor.getCount() < 1) {
			cursor.close();
			count = 0;
		} else {
			count = cursor.getCount();
		}
		cursor.close();
		return count;
	}

	private void createTable(String tablename, String id) {
		if (!tabIsExist(tablename)) {
			String stu_table = "create table " + tablename + "(_id integer primary key autoincrement, " + id
					+ " varchar(12))";
			db.execSQL(stu_table);
		}
	}

	/**
	 * 判断表是否存在
	 */
	public boolean tabIsExist(String tabName) {
		boolean result = false;
		if (tabName == null) {
			return false;
		}
		Cursor cursor = null;
		try {

			String sql = "select count(*) as c from sqlite_master where type ='table' and name ='" + tabName.trim()
					+ "' ";
			cursor = db.rawQuery(sql, null);
			if (cursor.moveToNext()) {
				int count = cursor.getInt(0);
				if (count > 0) {
					result = true;
				}
			}

		} catch (Exception e) {

		} finally {
			cursor.close();
		}
		return result;
	}

	/**
	 *
	 * @param tablename
	 * @param id
	 * @param value
	 */

	public void insertData(String tablename, String id, String value) {

		if (!queryData(tablename, id, value)) {
			String insertSql = "insert into " + tablename + "(" + id + ") values('" + value + "')";
			db.execSQL(insertSql);
		}

	}

	public boolean queryData(String tablename, String id, String value) {
		Cursor cursor = db.rawQuery("select * from " + tablename + " where " + id + "=?", new String[] { value });
		if (null == cursor || cursor.getCount() < 1) {
			cursor.close();
			return false;
		}
		cursor.close();
		return true;
	}

	/**
	 * 关闭数据库
	 */
	public void closeDatabase() {
		if (db != null)
			db.close();
	}

	/**
	 * 刷新指定页面
	 *
	 * @param
	 * @param flag
	 *            操作类型
	 * @param object
	 *            传递的数据
	 * @return 返回数据
	 */

	public Object notifyDataSetChanged(Class<?> clazz, int flag, Object object) {
		for (int i = 0, index = list.size(); i < index; i++) {
			if (list.get(i).getClass().getSimpleName().equals(clazz.getSimpleName())) {
				Object data = list.get(i).dataChang(flag, object);
				if (data != null)
					return data;
			}
		}
		return null;
	}

	/**
	 *可用EventBus代替
	 * @param
	 * @param flag
	 *            操作类型
	 * @return 返回数据
	 */
	public Object notifyDataSetChanged(Class<?> clazz, int flag) {
		return notifyDataSetChanged(clazz, flag, null);
	}

	/**
	 * 指定的activity是否已经存在实例
	 *
	 * @param clazz
	 * @return
	 */
	public boolean haveActivity(Class<?> clazz) {
		for (int i = 0, index = list.size(); i < index; i++) {
			if (list.get(i).getClass().getSimpleName().equals(clazz)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 添加对象
	 *
	 * @param baseInterFace
	 */
	public void addBaseInterFace(BaseInterFace baseInterFace) {
		if (!list.contains(baseInterFace)) {
			list.add(baseInterFace);
		} else {
			list.remove(baseInterFace);
			baseInterFace.finishActivity();
			list.add(baseInterFace);
		}
	}

	/**
	 * 移除对象
	 *
	 * @param baseInterFace
	 */
	public void reMoveBaseInterFace(BaseInterFace baseInterFace) {
		// list.remove(baseInterFace);
		Iterator<BaseInterFace> iterator = list.iterator();
		while (iterator.hasNext()) {
			BaseInterFace integer = iterator.next();
			if (baseInterFace == integer) {
				iterator.remove(); // 注意这个地方
				// integer.finishActivity();
				break;
			}
		}
	}

	/**
	 * 移除所有对象
	 *
	 */
	public void reMoveAllBaseInterFace() {
		// for (BaseInterFace baseInterFace : list) {
		// baseInterFace.finishActivity();
		// }
		// list.clear();

		try {

			Iterator<BaseInterFace> iterator = list.iterator();
			while (iterator.hasNext()) {
				BaseInterFace integer = iterator.next();
				iterator.remove(); // 注意这个地方
				integer.finishActivity();
			}
		} catch (Exception e) {

			Tools.showMessage("退出程序错误");
		}
	}

	/**
	 * 发起请求
	 *
	 * @param activity
	 * @param requestBean
	 * @param listener
	 */
	public void getPostData(Object activity, BaseBeanRequest requestBean, GetDataInterFace<String> listener,
							DisssmissInterFace disssmissListener) {
		PostRequest request = new PostRequest(Request.Method.POST, requestBean, listener, new GetDataErrorListener(
				disssmissListener));
		request.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
				DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
		if (activity != null)
			request.setTag(activity.getClass().getSimpleName());
		requestQueue.add(request);
	}

	/**
	 * 上传证件识别接口
	 *
	 * @param activity
	 * @param url
	 * @param listener
	 * @param disssmissListener
	 */

	public void getPostData(Object activity, String url, HashMap<String, String> map,
							GetDataInterFace<String> listener, DisssmissInterFace disssmissListener) {
		VolleyHttpUpLoad request = new VolleyHttpUpLoad(Request.Method.POST, url, map, listener,
				new GetDataErrorListener(disssmissListener));
		request.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
				DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
		if (activity != null)
			request.setTag(activity.getClass().getSimpleName());
		requestQueue.add(request);
	}

	/**
	 * 模拟网络数据
	 *
	 * @param listener
	 */

	public void getTestPostData(GetDataInterFace<String> listener) {
		String response = "";
		listener.onResponse(response);
	}

	/**
	 * 取消请求
	 *
	 * @param tag
	 */
	public void reMoveRequest(Object tag) {
		if (requestQueue != null && tag != null) {
			requestQueue.cancelAll(tag.getClass().getSimpleName());
		}
	}

}
